import { PlusOutlined, InfoCircleOutlined, ReloadOutlined, RollbackOutlined } from '@ant-design/icons'
import { message, Tooltip } from 'antd'
import { Button, Input, Space, Form, Select } from 'antd'
import styles from './index.module.scss'
import SignKeywords from './components/SignKeywords'
import { getCategoryListAPI, getSignInfoAPI } from 'api'
import { useEffect, useRef, useState } from 'react'
import { useAppDispatch } from 'store/hook'
import { addSignAsync, editSign } from 'store/slices/signSlice'
import { useNavigate, useSearchParams } from 'react-router-dom'
import pinyingMatch from 'pinyin-match'

export default function CustomSign() {
  const [form] = Form.useForm<Sign>()
  const [categoryList, setCategoryList] = useState<Category[]>([])
  const dispatch = useAppDispatch()
  const navigate = useNavigate()
  const params = useSearchParams()[0]
  const id = useRef(Number(params.get('id')))

  // 新增或修改
  const onFinish = async (values: Sign) => {
    if (id.current) {
      await dispatch(editSign({ ...values, id: id.current }))
      message.success('修改成功！')
    } else {
      await dispatch(addSignAsync(values))
      message.success('添加成功！')
      // 重置表单
      form.resetFields()
      // 跳转符号查询页
      navigate('/')
    }
  }

  // 获取符号类别列表
  const getCategoryList = async () => {
    const list = await getCategoryListAPI<Category>()
    setCategoryList(list)
  }

  // 获取符号信息
  const getSignInfo = async () => {
    const { data } = await getSignInfoAPI(id.current)
    data && form.setFieldsValue(data)
  }

  useEffect(() => {
    getCategoryList()
    id.current && getSignInfo()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <div className={styles['custom-sign']}>
      <h2 className='p10 tac'>自定义符号</h2>
      <Form
        autoComplete='off'
        form={form}
        labelCol={{ span: 6 }}
        labelWrap
        wrapperCol={{ span: 12 }}
        // initialValues={{
        //   sign: '©',
        //   signName: 'copyright',
        //   signKeywords: 'copyright,copying,版权,著作权,版权所有,版权声明,授权',
        //   categoryId: 1
        // }}
        size='large'
        onFinish={onFinish}>
        <Form.Item label='符号' name='sign' rules={[{ required: true, message: '请填充符号！' }]}>
          <Input showCount maxLength={10} allowClear />
        </Form.Item>
        <Form.Item label='符号名称' name='signName' rules={[{ required: true, message: '请输入符号名称！（建议使用英文）' }]}>
          <Input showCount maxLength={30} allowClear />
        </Form.Item>
        <Form.Item
          label={
            <span>
              符号关键字
              <Tooltip
                title={
                  <>
                    <div>Tip1：使用英文逗号（,）或中文逗号（，）或竖杠（|）分隔关键字可进行批量添加！</div> {/* <div>Tip2：关键字个数不能超过 20 个！</div> */}
                  </>
                }
                color='#55acee'
                placement='topRight'>
                <InfoCircleOutlined className='ml5' style={{ color: 'orange' }} />
              </Tooltip>
            </span>
          }
          name='signKeywords'
          rules={[{ required: true, message: '请添加符号关键字！' }]}>
          <SignKeywords />
        </Form.Item>
        <Form.Item label='所属类别' name='categoryId' rules={[{ required: true, message: '请选择所属类别！' }]}>
          <Select
            allowClear
            showSearch
            placeholder='选择/搜索'
            optionFilterProp='children'
            filterOption={(input, option) => {
              const lowerInput = input.toLowerCase()
              return (option!.children as unknown as string).includes(lowerInput) || pinyingMatch.match(option?.children, lowerInput)
            }}
            filterSort={(optionA, optionB) => (optionA!.children as unknown as string).toLowerCase().localeCompare((optionB!.children as unknown as string).toLowerCase())}>
            {categoryList.map(item => (
              <Select.Option key={item.id} value={item.id}>
                {item.categoryNameZh}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 6, span: 12 }}>
          <Space>
            <Button type='primary' block htmlType='submit'>
              <PlusOutlined /> {id.current ? '修改' : '新增'}
            </Button>
            <Button type='primary' block icon={<ReloadOutlined />} onClick={() => form.resetFields()}>
              重置
            </Button>
            <Button hidden={!id.current} icon={<RollbackOutlined />} onClick={() => navigate(-1)}>
              返回
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </div>
  )
}
